import { Injectable } from '@angular/core';
import { MessageService } from './message.service';
import { Observable ,of } from 'rxjs';
import { catchError,map,tap} from 'rxjs/operators'
import { HttpClient,HttpHeaders } from '@angular/common/http'

import { Login } from './login';
import { LOGINS } from './mock-logins';

const httpOptions = {
  	header: new HttpHeaders({'Content-Type':'application/json'})	
}
@Injectable({
  providedIn: 'root'
})
export class LoginService {
  	private loginUrl = 'api/login';	
  	private log(message:string){
		this.messageService.add('LoginService:${message}')
	}
	private handleError<T>(operation = 'operation',result ? : T){
		return (error : any ): Observable<T> =>{
			console.error(error);
			this.log('${operation} failed : ${error.message}');
			return of(result as T);
		}
	}
  	constructor(
  		private http : HttpClient,
  		private messageService : MessageService) {

  	}
  	getLogins(): Observable<Login[]> {
  		return this.http.get<Login[]>(this.loginUrl).pipe(
  			tap(_=>this.log('fetched logins')),
  			catchError(this.handleError('getLogins',[]))
  		)
  		
  		//this.messageService.add('HeroService: fetched heroes');
    	return of(LOGINS);
  	}
    login(userToken: string): Observable<any> {
    let httpOptions: any;
    httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': userToken
      })
    };
    let url = this.loginUrl;
    return this.http
      .get(url,httpOptions)
      .pipe(
        tap((res: any) => res),
        catchError((error: Response | any) => {
          return Promise.reject(error);
        })
      );
  }
}
